package com.qing.expert.modules.expert.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qing.expert.common.exception.BusinessException;
import com.qing.expert.modules.expert.entity.ExpertRating;
import com.qing.expert.modules.expert.mapper.ExpertRatingMapper;
import com.qing.expert.modules.expert.service.ExpertRatingService;
import com.qing.expert.modules.expert.vo.response.ExpertRatingVO;
import com.qing.expert.modules.order.entity.Order;
import com.qing.expert.modules.order.mapper.OrderMapper;
import com.qing.expert.modules.user.entity.User;
import com.qing.expert.modules.user.mapper.UserMapper;
import com.qing.expert.modules.expert.mapper.ExpertMapper;
import com.qing.expert.modules.expert.entity.Expert;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ExpertRatingServiceImpl implements ExpertRatingService {

    @Resource
    private ExpertRatingMapper expertRatingMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ExpertMapper expertMapper;

    @Override
    public List<ExpertRatingVO> getRatingList(String expertId) {
        // 查询评价列表
        List<ExpertRating> list = expertRatingMapper.selectList(
                new LambdaQueryWrapper<ExpertRating>()
                        .eq(ExpertRating::getExpertId, expertId)
                        .orderByDesc(ExpertRating::getCreateTime));

        // 转换为VO
        List<ExpertRatingVO> voList = new ArrayList<>();
        for (ExpertRating rating : list) {
            ExpertRatingVO vo = new ExpertRatingVO();
            BeanUtils.copyProperties(rating, vo);

            // 获取用户信息
            User user = userMapper.selectById(rating.getUserId());
            if (user != null) {
                vo.setUserName(user.getNickname());
                vo.setUserAvatar(user.getAvatar());
            }

            // 设置时间描述
            vo.setCreateTimeDesc(getTimeDesc(rating.getCreateTime()));
            voList.add(vo);
        }

        return voList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitRating(String userId, String orderId, Integer rating, String comment) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 检查是否是订单所属用户
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权操作此订单");
        }

        // 检查订单状态
        if (order.getStatus() != 3) { // 3=已完成
            throw new BusinessException("订单未完成,不能评价");
        }

        // 检查是否已评价
        Long count = expertRatingMapper.selectCount(
                new LambdaQueryWrapper<ExpertRating>()
                        .eq(ExpertRating::getOrderId, orderId));
        if (count > 0) {
            throw new BusinessException("该订单已评价");
        }

        // 1. 创建评价
        ExpertRating expertRating = new ExpertRating()
                .setRatingId(IdUtil.getSnowflakeNextIdStr())
                .setOrderId(orderId)
                .setExpertId(order.getExpertId())
                .setUserId(userId)
                .setRating(rating)
                .setComment(comment)
                .setCreateTime(LocalDateTime.now());

        expertRatingMapper.insert(expertRating);

        // 2. 更新订单状态为已评价 (4=已评价)
        order.setStatus(4);
        orderMapper.updateById(order);

        // 3. 更新达人的平均评分
        Double avgRating = expertRatingMapper.getAverageRating(order.getExpertId());
        Expert expert = expertMapper.selectById(order.getExpertId());
        if (expert != null) {
            expert.setRating(avgRating);
            expertMapper.updateById(expert);
        }

        log.info("用户[{}]对订单[{}]进行了评价，更新达人[{}]平均评分为: {}",
                userId, orderId, order.getExpertId(), avgRating);
    }

    @Override
    public Double getExpertRating(String expertId) {
        return expertRatingMapper.getAverageRating(expertId);
    }

    /**
     * 获取时间描述
     */
    private String getTimeDesc(LocalDateTime time) {
        LocalDateTime now = LocalDateTime.now();
        long minutes = java.time.Duration.between(time, now).toMinutes();
        if (minutes < 60) {
            return minutes + "分钟前";
        }
        long hours = minutes / 60;
        if (hours < 24) {
            return hours + "小时前";
        }
        return DateUtil.format(java.util.Date.from(time.atZone(java.time.ZoneId.systemDefault()).toInstant()),
                "MM-dd HH:mm");
    }
}